<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>讲解员报名管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.7.6/dist/css/layui.css">
    <style>
        .layui-table-cell {
            height: auto;
            line-height: 1.6;
        }
        .status-badge {
            padding: 2px 8px;
            border-radius: 3px;
            color: #fff;
            font-size: 12px;
        }
        .status-pending { background-color: #ff9800; }
        .status-approved { background-color: #4caf50; }
        .status-rejected { background-color: #f44336; }
        .image-preview img {
            max-width: 100px;
            max-height: 100px;
            margin: 5px;
            border-radius: 5px;
        }
        .detail-panel {
            padding: 20px;
            background: #f8f8f8;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .detail-item {
            margin-bottom: 10px;
        }
        .detail-label {
            font-weight: bold;
            color: #333;
            width: 120px;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="layui-container" style="margin-top: 20px;">
        <div class="layui-row">
            <div class="layui-col-xs12">
                <!-- 页面标题和操作区 -->
                <div class="layui-card">
                    <div class="layui-card-header">
                        <h2>讲解员报名管理</h2>
                        <div class="layui-btn-group" style="float: right;">
                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="refreshBtn">
                                <i class="layui-icon layui-icon-refresh"></i> 刷新
                            </button>
                            <button class="layui-btn layui-btn-normal layui-btn-sm" id="exportBtn">
                                <i class="layui-icon layui-icon-export"></i> 导出
                            </button>
                        </div>
                    </div>
                    <div class="layui-card-body">
                        <!-- 搜索区域 -->
                        <div class="layui-form layui-form-pane" id="searchForm">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">状态</label>
                                    <div class="layui-input-inline">
                                        <select name="status" lay-search="">
                                            <option value="">全部状态</option>
                                            <option value="0">待审核</option>
                                            <option value="1">已通过</option>
                                            <option value="2">已拒绝</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">性别</label>
                                    <div class="layui-input-inline">
                                        <select name="gender" lay-search="">
                                            <option value="">全部性别</option>
                                            <option value="male">男</option>
                                            <option value="female">女</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">院系</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="department" placeholder="请输入院系" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">关键词</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="search" placeholder="姓名/手机号/学号" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn" lay-submit lay-filter="searchSubmit">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 统计面板 -->
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-panel">
                            <div style="padding: 20px; text-align: center;">
                                <div style="font-size: 24px; color: #1E9FFF;" id="totalCount">0</div>
                                <div>总申请数</div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-panel">
                            <div style="padding: 20px; text-align: center;">
                                <div style="font-size: 24px; color: #FF9800;" id="pendingCount">0</div>
                                <div>待审核</div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-panel">
                            <div style="padding: 20px; text-align: center;">
                                <div style="font-size: 24px; color: #4CAF50;" id="approvedCount">0</div>
                                <div>已通过</div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-panel">
                            <div style="padding: 20px; text-align: center;">
                                <div style="font-size: 24px; color: #F44336;" id="rejectedCount">0</div>
                                <div>已拒绝</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 数据表格 -->
                <div class="layui-card" style="margin-top: 15px;">
                    <div class="layui-card-body">
                        <table class="layui-hide" id="volunteerTable" lay-filter="volunteerTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 工具栏模板 -->
    <script type="text/html" id="toolbarTpl">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-warm layui-btn-sm" lay-event="batchApprove">
                <i class="layui-icon layui-icon-ok"></i>批量通过
            </button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="batchReject">
                <i class="layui-icon layui-icon-close"></i>批量拒绝
            </button>
        </div>
    </script>

    <!-- 操作栏模板 -->
    <script type="text/html" id="operationTpl">
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-xs" lay-event="detail">详情</button>
            {{# if(d.status == 0) { }}
                <button class="layui-btn layui-btn-warm layui-btn-xs" lay-event="approve">通过</button>
                <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="reject">拒绝</button>
            {{# } }}
            <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</button>
        </div>
    </script>

    <!-- 状态模板 -->
    <script type="text/html" id="statusTpl">
        {{# if(d.status == 0) { }}
            <span class="status-badge status-pending">待审核</span>
        {{# } else if(d.status == 1) { }}
            <span class="status-badge status-approved">已通过</span>
        {{# } else if(d.status == 2) { }}
            <span class="status-badge status-rejected">已拒绝</span>
        {{# } }}
    </script>

    <script src="https://cdn.jsdelivr.net/npm/layui@2.7.6/dist/layui.js"></script>
    <script>
    layui.use(['table', 'form', 'layer', 'element', 'util'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var element = layui.element;
        var util = layui.util;

        // API 配置
        const API = {
            list: '/api/admin/volunteer_management.php?action=list',
            detail: '/api/admin/volunteer_management.php?action=detail',
            review: '/api/admin/volunteer_management.php?action=review',
            batchReview: '/api/admin/volunteer_management.php?action=batch_review',
            delete: '/api/admin/volunteer_management.php',
            stats: '/api/admin/volunteer_management.php?action=stats'
        };

        // 表格配置
        const tableConfig = {
            elem: '#volunteerTable',
            url: API.list,
            toolbar: '#toolbarTpl',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [[
                {type: 'checkbox', width: 50},
                {field: 'id', title: 'ID', width: 80, sort: true},
                {field: 'name', title: '姓名', width: 100},
                {field: 'gender_text', title: '性别', width: 80},
                {field: 'phone', title: '手机号', width: 130},
                {field: 'student_id', title: '学号', width: 120},
                {field: 'department', title: '院系', width: 150},
                {field: 'grade', title: '年级', width: 100},
                {field: 'status', title: '状态', width: 100, templet: '#statusTpl'},
                {field: 'user_name', title: '用户信息', width: 120},
                {field: 'created_at', title: '申请时间', width: 160, sort: true},
                {title: '操作', width: 200, align: 'center', toolbar: '#operationTpl'}
            ]],
            page: true,
            height: 'full-320',
            parseData: function(res) {
                return {
                    "code": res.success ? 0 : 1,
                    "msg": res.message || '',
                    "count": res.data ? res.data.pagination.total : 0,
                    "data": res.data ? res.data.list : []
                };
            }
        };

        // 初始化表格
        table.render(tableConfig);

        // 加载统计数据
        function loadStats() {
            fetch(API.stats)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data) {
                        const stats = data.data.total_stats;
                        document.getElementById('totalCount').textContent = stats.total || 0;
                        document.getElementById('pendingCount').textContent = stats.pending_count || 0;
                        document.getElementById('approvedCount').textContent = stats.approved_count || 0;
                        document.getElementById('rejectedCount').textContent = stats.rejected_count || 0;
                    }
                })
                .catch(error => {
                    console.error('加载统计数据失败:', error);
                });
        }

        // 页面加载时获取统计数据
        loadStats();

        // 搜索表单提交
        form.on('submit(searchSubmit)', function(data) {
            table.reload('volunteerTable', {
                where: data.field,
                page: {curr: 1}
            });
            return false;
        });

        // 工具栏事件
        table.on('toolbar(volunteerTable)', function(obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            
            switch(obj.event) {
                case 'batchApprove':
                    if (data.length === 0) {
                        layer.msg('请选择要操作的数据');
                        return;
                    }
                    batchReview(data, 1, '批量通过');
                    break;
                case 'batchReject':
                    if (data.length === 0) {
                        layer.msg('请选择要操作的数据');
                        return;
                    }
                    layer.prompt({
                        formType: 2,
                        title: '请输入拒绝原因',
                        area: ['400px', '200px']
                    }, function(value, index) {
                        batchReview(data, 2, '批量拒绝', value);
                        layer.close(index);
                    });
                    break;
            }
        });

        // 行工具事件
        table.on('tool(volunteerTable)', function(obj) {
            var data = obj.data;
            
            switch(obj.event) {
                case 'detail':
                    showDetail(data.id);
                    break;
                case 'approve':
                    reviewVolunteer(data.id, 1, '', '通过申请');
                    break;
                case 'reject':
                    layer.prompt({
                        formType: 2,
                        title: '请输入拒绝原因',
                        area: ['400px', '200px']
                    }, function(value, index) {
                        reviewVolunteer(data.id, 2, value, '拒绝申请');
                        layer.close(index);
                    });
                    break;
                case 'delete':
                    layer.confirm('确定要删除这条申请吗？', function(index) {
                        deleteVolunteer(data.id);
                        layer.close(index);
                    });
                    break;
            }
        });

        // 显示详情
        function showDetail(id) {
            fetch(API.detail + '&id=' + id)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const volunteer = data.data;
                        const content = `
                            <div class="detail-panel">
                                <div class="detail-item">
                                    <span class="detail-label">姓名：</span>${volunteer.name || '-'}
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">性别：</span>${volunteer.gender_text || '-'}
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">手机号：</span>${volunteer.phone || '-'}
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">学号：</span>${volunteer.student_id || '-'}
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">院系：</span>${volunteer.department || '-'}
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">年级：</span>${volunteer.grade || '-'}
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">相关经验：</span>
                                    <div style="margin-top: 5px; padding: 10px; background: #fff; border-radius: 3px;">
                                        ${volunteer.experience || '无'}
                                    </div>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">可服务时间：</span>
                                    <div style="margin-top: 5px; padding: 10px; background: #fff; border-radius: 3px;">
                                        ${volunteer.available_time || '无'}
                                    </div>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">自我介绍：</span>
                                    <div style="margin-top: 5px; padding: 10px; background: #fff; border-radius: 3px;">
                                        ${volunteer.self_introduction || '无'}
                                    </div>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">状态：</span>${volunteer.status_text || '-'}
                                </div>
                                ${volunteer.review_note ? `
                                <div class="detail-item">
                                    <span class="detail-label">审核备注：</span>
                                    <div style="margin-top: 5px; padding: 10px; background: #fff; border-radius: 3px;">
                                        ${volunteer.review_note}
                                    </div>
                                </div>
                                ` : ''}
                                <div class="detail-item">
                                    <span class="detail-label">申请时间：</span>${volunteer.created_at || '-'}
                                </div>
                            </div>
                        `;
                        
                        layer.open({
                            type: 1,
                            title: '申请详情',
                            area: ['600px', '500px'],
                            content: content,
                            btn: ['关闭'],
                            yes: function(index) {
                                layer.close(index);
                            }
                        });
                    } else {
                        layer.msg('获取详情失败：' + data.message);
                    }
                })
                .catch(error => {
                    layer.msg('网络错误');
                });
        }

        // 审核申请
        function reviewVolunteer(id, status, reviewNote, actionName) {
            const requestData = {
                id: id,
                status: status,
                review_note: reviewNote || ''
            };

            fetch(API.review, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    layer.msg(actionName + '成功');
                    table.reload('volunteerTable');
                    loadStats();
                } else {
                    layer.msg(actionName + '失败：' + data.message);
                }
            })
            .catch(error => {
                layer.msg('网络错误');
            });
        }

        // 批量审核
        function batchReview(data, status, actionName, reviewNote) {
            const ids = data.map(item => item.id);
            const requestData = {
                ids: ids,
                status: status,
                review_note: reviewNote || ''
            };

            fetch(API.batchReview, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    layer.msg(actionName + '成功');
                    table.reload('volunteerTable');
                    loadStats();
                } else {
                    layer.msg(actionName + '失败：' + data.message);
                }
            })
            .catch(error => {
                layer.msg('网络错误');
            });
        }

        // 删除申请
        function deleteVolunteer(id) {
            fetch(API.delete + '?id=' + id, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    layer.msg('删除成功');
                    table.reload('volunteerTable');
                    loadStats();
                } else {
                    layer.msg('删除失败：' + data.message);
                }
            })
            .catch(error => {
                layer.msg('网络错误');
            });
        }

        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', function() {
            table.reload('volunteerTable');
            loadStats();
            layer.msg('已刷新');
        });

        // 导出按钮
        document.getElementById('exportBtn').addEventListener('click', function() {
            layer.msg('导出功能开发中...');
        });
    });
    </script>
</body>
</html>